using System;
using System.Collections.Generic;
using Utils.Extends;
using UnityEngine;
using Utils;

namespace Core
{
    public abstract class GameSubsystem : MonoBehaviour
    {
        private static Dictionary<Type, GameSubsystem> _subsystems = new Dictionary<Type, GameSubsystem>();

        public static T Find<T>() where T : GameSubsystem
        {
            if (_subsystems.ContainsKey(typeof(T)))
                return _subsystems[typeof(T)] as T;
            T temp = Resources.Load<T>(typeof(T).Name);
            return temp.CreateInstance();
        }

        protected virtual void Awake()
        {
            if (_subsystems.ContainsKey(GetType()))
            {
                Destroy(this);
                LogHelper.Warning($"子系统 '{GetType().Name}' 已经存在，游戏物体 '{gameObject.name}' 的实例已被销毁。", this);
            }
            else
            {
                _subsystems.Add(GetType(), this);
            }
        }

        protected virtual void OnDestroy()
        {
            _subsystems.Remove(GetType());
        }
    }
}